<template>
  <div class="app-container">
    <!-- 删除/恢复 -->
    <el-dialog :title="targetTitle" size="small" :visible.sync="showDelDialog" @close="closeDialogHandler">
      <el-button @click="showDelDialog = false" size="small">否</el-button>
      <el-button type="primary" @click="statusHandler" size="small">是</el-button>
    </el-dialog>
    <!-- 添加 -->
    <el-dialog title="添加新的主题" size="small" :visible.sync="showAddDialog" @close="closeDialogHandler">
      <theme-add :pid="pid" v-on:close="closeDialogHandler"></theme-add>
    </el-dialog>
    <!-- 编辑 -->
    <el-dialog title="编辑的主题" size="small" :visible.sync="showEditDialog" @close="closeDialogHandler">
      <theme-edit :theme="target" v-on:close="closeDialogHandler"></theme-edit>
    </el-dialog>

    <div style="margin-bottom: 16px;">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item v-for="item in pageParent" :key="item.id">
          <el-button type="text" :disabled="item.disable" style="padding-bottom: 0px;" @click="goParent(item.id)">{{ item.name }} </el-button>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!-- 操作表单 -->
    <div class="op-form">
      <el-form :inline="formInline" class="demo-ruleForm">
        <div>
          <el-form-item label="" label-width="80px">
            <el-input v-model="searchKey" placeholder="主题名称" @keyup.enter.native="seachHandler" style="width: 300px;">
              <el-button slot="append" icon="el-icon-search" @click="seachHandler">搜索</el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="状态" label-width="50px">
            <el-select placeholder="状态" v-model="status">
              <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div style="border-top:1px dashed #CCCCCC; padding-top: 10px;">
          <el-button type="primary" size="small" @click="onAdd">添加主题</el-button>
        </div>
      </el-form>
    </div>
    <el-table :data="list" v-loading.body="loading" @sort-change="sortHandler" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column align="center" fixed="left" sortable="true" prop="id" label='ID' width="95">
        <template slot-scope="scope">
          {{scope.row.id}}
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="left" prop="name" label='名称' width="95">
        <template slot-scope="scope">
          {{scope.row.name}}
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="状态" width="80" align="center">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.status == 1">正常</el-tag>
          <el-tag type="danger" v-else>已删除</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" sortable="true" prop="create_time" label="发布时间" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span>{{scope.row.create_time}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" sortable="true" prop="update_time" label="更新时间" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time"></i>
          <span>{{scope.row.update_time}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" prop="update_time" label="操作" width="120">
        <template slot-scope="scope">
          <span>
            <el-dropdown size="small" split-button type="primary" @command="opHandler">
            操作
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="scope.row.cmd_del">
                <span v-if="scope.row.status == 0">恢复</span>
                <span v-else>删除</span>
              </el-dropdown-item>
              <el-dropdown-item :command="scope.row.cmd_edit">
                <span>编辑</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          </span>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 10px; margin-left: -10px;">
      <el-pagination ref="pagination" 
        background 
        :page-size="pageSize"
        :current-page="page" 
        :pager-count="21" 
        @current-change="pageChange" 
        layout="prev, pager, next"
        :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { getList, setStatus } from '@/api/theme'
import ThemeAdd from './component/themeAdd'
import ThemeEdit from './component/themeEdit'
export default {
  data() {
    return {
      // 对话框
      showDelDialog: false,
      showAddDialog: false,
      showEditDialog: false,
      // 目标信息
      targetTitle:'',
      targetId: 0,
      target: undefined,
      formInline: true,
      list: [],
      loading: true,
      pageSize: 0,
      total: 0,
      executeQuery: false,
      pageParent: [
        {
          id: 0,
          name: '最顶级',
          query: undefined,
          disable: true
        }
      ],
      pid: '0',
      page: 1,
      searchKey: '',
      level: '0',
      status: '2',
      statusOptions: [
        {
          value: '0',
          label: '已删除'
        },
        {
          value: '1',
          label: '正常'
        },
        {
          value: '2',
          label: '全部'
        }
      ],
      osc: 'DESC',
      orderKey: 'id'
    }
  },
  watch: {
    executeQuery: function(nv, ov) {
      if (nv) {
        // 如果为true, 则执行查询
        this.fetchData()
      }
    }
  },
  components: {
    'theme-add': ThemeAdd,
    'theme-edit': ThemeEdit
  },
  computed: {
    disableBreadcrumbBtn(idx) {
      if (idx == this.pageParent.length - 1) {
        return true
      } else {
        return false
      }
    }
  },
  mounted() {
    // 初始化其它参数
    this.searchKey = ''
    this.osc = 'DESC'   //  降序
    this.orderKey = 'id'// 按id排序
    this.status = '2'   //  正常和删除混合
    this.level = '1'    //  等级, 默认为1(最顶级, 然后一层层向下)
    this.page = 1       //  第一页
    this.pageParent[0].query = this.buildListQuery(0)
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.loading = true
      let query = this.buildListQuery()
      getList(query).then(res => {
        this.pageSize = res.page_size
        this.total = res.total
        this.loading = false
        this.executeQuery = false
        this.list = res.items
        // 更新分页器的内部当前页
        this.$refs.pagination.internalCurrentPage = this.page
      }).catch( (err) => { 
        this.loading = false
        this.executeQuery = false
      })
    },
    opHandler(command) {
      const cmdInfo = command.split(':')
      switch (cmdInfo[0]) {
        case 'del':
          this.targetId = cmdInfo[1]
          // 查找名字
          let target = this.findItemById(this.targetId)
          console.log(target)
          if (target !== undefined) {
            this.buildStatusInfo(target)
          }
          this.showDelDialog = true
          break
        case 'edit':
          console.log('EDIT')
          this.targetId = cmdInfo[1]
          console.log(this.targetId)
          // 查找名字
          this.target = this.findItemById(this.targetId)
          console.log(this.target)
          if (this.target !== undefined) {
            this.showEditDialog = true  
          } else {
            // this.target = undefined
          }
          break
        default:
          console.log('no law command')
      }
    },
    sortHandler(sortInfo) {
      this.orderKey= sortInfo.prop
      if (sortInfo.order === "descending") {
        this.osc = "DESC"
      } else {
        this.osc = "ASC"
      }
      this.executeQuery = true
    },
    pageChange(page) {
      this.page = page
      this.executeQuery = true
    },
    // 删除
    statusHandler() {
      // 更新状态
      setStatus(this.targetId).then(response => {
          this.fetchData()
          this.targetId = 0
          this.targetTitle = ''
          this.showDelDialog = false
      })
    },
    editHandler() {
      console.log("set theme edit:"+this.pid)
      this.showAddDialog = true
    },
    onAdd() {
      this.showAddDialog = true
    },
    // 搜索
    seachHandler() {
      this.executeQuery = true
    },
    // 构建查询结构
    buildListQuery(type = 1) {
      // 返回数据
      return {
        name: this.searchKey,
        orderKey: this.orderKey,
        osc: this.osc,
        page: this.page,
        level: this.level,
        status: this.status,
        pid: this.pid
      }
    },
    closeDialogHandler() {
      this.showDelDialog = false
      this.showAddDialog = false
      this.showEditDialog = false
      this.targetId = 0
      this.targetTitle = ''
      this.executeQuery = true
    },
    showSubThemes(pid, count) {
      if (count > 0) {
        this.$router.push({path: '/theme/sub?pid='+pid})
      } else {
        this.$message.warning('没有子主题')
      }
    },
    // 在列表中查找项目
    findItemById(id) {
      let target = undefined
      // 查找名字
      for(let i = 0; i < this.list.length; i++) {
        if (this.list[i].id == this.targetId) {
          target = this.list[i]
          break;
        }
      }
      return target
    },
    buildStatusInfo(target) {
      this.targetTitle = '是否'
      if (target.status == 0) {
        this.targetTitle += '恢复'
      } else {
        this.targetTitle += '删除'
      }
      this.targetTitle += '群组"' + target.name+'"'
    },
    showSubList(item) {
      if (item.subcount == 0) {
        this.$message.warning('该主题下午任何子主题')
      } else {
        // 获取数据
        let lastIdx = this.pageParent.length - 1
        let nowQuery = this.buildListQuery()
        this.pageParent[lastIdx].query = nowQuery
        this.pageParent[lastIdx].disable = false
        
        // 更新页面刷新参数
        this.pid = item.id
        this.page = 1
        this.level = '1'
        this.searchKey = ''
        let newQuery = this.buildListQuery()
        this.pageParent.push({id: item.id, query: newQuery, name: item.name, disable: true})
        this.executeQuery = true
      }
    },
    // 到上一层中
    goParent(id) {
      let p = undefined
      let executePop = false
      // 查找目标id的pageParent
      let popFromIdx = -1
      for (let i = 0; i < this.pageParent.length; i++) {
        console.log('route-id:'+this.pageParent[i].id+', find-id:'+id)
        if(this.pageParent[i].id == id) {
          p = this.pageParent[i]
          popFromIdx = i
          // 删除剩余的标签
          // executePop = true
        } 
      }
      if (popFromIdx > -1) {
        for (let i = this.pageParent.length - 1; i > popFromIdx; i--) {
          this.pageParent.pop()
        }
      }
      

      // 检查是否查找到该parent
      if (p !== undefined) {
        this.page = p.query.page
        this.pid = p.query.pid
        this.level = p.query.level
        this.status = p.query.status
        this.searchKey = p.query.searchKey
        this.orderKey = p.query.orderKey
        this.osc = p.query.osc
        this.executeQuery = true  
      }
    },
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  .avatar-img {
    width: 40px;
    height: 40px;
    border-radius: 100px;
    // box-shadow:0px 2px 1px 1px #C3C3C3;
  }
  .el-button--text {
    padding-top: 0px;
    color: #7C796E;
  }
  .op-form {
    background: #F5F9FF;
    border: 1px dashed #CCCCCC;
    border-radius: 5px;
    padding: 10px;
    margin-bottom: 12px;
  }
  .slider-container {
    background-color: #F5F9FF;
    border: 1px solid #DCDFE6;
    padding: 5px;
    border-radius: 10px;
    margin-bottom: 10px;
  }
  .el-form-item {
    margin-bottom: 10px;
  }
  .el-dialog__wrapper {
    .el-dialog {
      border-radius: 10px;
    }
  }
  
</style>

